// $(function () {
//     initSysModeTable();
// })
var grid;
$(document).ready(function() {
    /////////////jehc扩展属性目的可方便使用（boot.js文件datatablesCallBack方法使用） 如弹窗分页查找根据条件 可能此时的form发生变化 此时 可以解决该类问题
    var opt = {
        searchformId:'searchForm'
    };
    var options = DataTablesPaging.pagingOptions({
        ajax:function (data, callback, settings){datatablesCallBack(data, callback, settings,oauthModules+'/oauthSysMode/list',opt);},//渲染数据
        //在第一位置追加序列号
        fnRowCallback:function(nRow, aData, iDisplayIndex){
            jQuery('td:eq(1)', nRow).html("<span class='row-details la la-plus' data_id='"+aData.sys_mode_id+"' sysname='"+aData.sysname+"'></span> ");
            return nRow;
        },
        order:[],//取消默认排序查询,否则复选框一列会出现小箭头
        tableHeight:datatablesDefaultHeight,
        //列表表头字段
        colums:[
            {
                sClass:"text-center",
                width:"50px",
                data:"sys_mode_id",
                render:function (data, type, full, meta) {
                    return '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline"><input type="checkbox" name="checkId" class="checkchild " value="' + data + '" /><span></span></label>';
                },
                bSortable:false
            },
            {
                data:"sys_mode_id",
                width:"50px"
            },
            {
                data:'sysname',
                width:"50px"
            },
            {
                data:'sys_mode_status',
                width:"50px",
                render:function(data, type, row, meta) {
                    if(data == 0){
                        return "<span class='m-badge m-badge--info'>正常</span>"
                    }
                    if(data == 1){
                        return "<span class='m-badge m-badge--success'>冻结</span>"
                    }
                    if(data == 2){
                        return "<span class='m-badge m-badge--danger'>禁用</span>"
                    }
                    return "<span class='m-badge m-badge--info'>缺省</span>"
                }
            },
            {
                data:"createBy",
                width:"150px",
                render:function(data, type, row, meta) {
                    if(null == data || data == ''){
                        return "<font color='#6495ed'>\</font>";
                    }
                    return data;
                }
            },
            {
                data:"create_time",
                width:"150px",
                render:function(data, type, row, meta) {
                    return dateformat(data);
                }
            },
            {
                data:"modifiedBy",
                width:"150px",
                render:function(data, type, row, meta) {
                    if(null == data || data == ''){
                        return "<font color='#6495ed'>\</font>";
                    }
                    return data;
                }
            },
            {
                data:"update_time",
                width:"150px",
                render:function(data, type, row, meta) {
                    return dateformat(data);
                }
            },
            {
                data:"sys_mode_id",
                render:function(data, type, row, meta) {
                    var sysname =  row.sysname;
                    var sys_mode_status =  row.sys_mode_status;
                    var btn = '<button onclick=detail("'+sysname+'","'+sys_mode_status+'") class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="详情"><i class="m-menu__link-icon la la-eye"></i></button>'
                    return btn;
                }
            }
        ]
    });
    grid=$('#datatables').dataTable(options);
    //实现全选反选
    docheckboxall('checkall','checkchild');
    //实现单击行选中
    clickrowselected('datatables');
    $('.table').on('click', ' tbody td .row-details', function () {
        var nTr = $(this).parents('tr')[0];
        if ( grid.fnIsOpen(nTr) )//判断是否已打开
        {
            /* This row is already open - close it */
            $(this).addClass("la-plus").removeClass("la-minus");
            grid.fnClose( nTr );
        }else{
            /* Open this row */
            $(this).addClass("la-minus").removeClass("la-plus");
            // 调用方法显示详细信息 data_id为自定义属性 存放配置ID
            initTreeTable(nTr,$(this).attr("data_id"),$(this).attr("sysname"));
        }
    });
});

function detail(sysname,sys_mode_status){
    var sysname = "隶属平台:"+sysname;
    if(sys_mode_status == 0){
        sys_mode_status = "正常";
    }else if(sys_mode_status == 1){
        sys_mode_status = "冻结";
    }else if(sys_mode_status == 2){
        sys_mode_status = "禁用";
    }else{
        sys_mode_status = "缺省";
    }
    sys_mode_status = "状态:"+sys_mode_status;
    window.parent.toastrBoot(1,sysname+"<br>"+sys_mode_status);
}

/**
 * 初始化 Tree Table
 * @param tableId
 * @param row
 */
function initTreeTable(nTr,pdataId,sysname){
    var sOut = "<div style='text-align: center;border:1px; '><table  id="+pdataId+" style='width: 80%;margin: auto;'></table></div>";
    grid.fnOpen( nTr,sOut, 'details' );
    dialogWating = showWating({msg:'正在拼命的加载中...'});
    $.ajax({
        url:oauthModules+'/oauthResources/all/list?sys_mode_id='+pdataId,
        type:"GET",
        dataType:"json",
        success:function(data) {
            var $table = $("#"+pdataId);
            data = eval("(" + data.data + ")");
            $table.bootstrapTable('destroy').bootstrapTable({
                data:data,
                striped:false,
                class:'table table-hover table-bordered',
                sidePagination:"client",//表示服务端请求
                pagination:false,
                treeView:true,
                treeId:"id",
                // height:tableHeight()*0.7,
                treeField:"name",
                sortable:false,//是否启用排序
                columns:[
                    /* 
                    {
                        field: 'ck',
                        checkbox:true
                    }, 
                    */
                    {
                        field:'name',
                        width:270,
                        title:'名称',
                        formatter:'nameFormatter'
                    },
                    {
                        field:'tempObject',
                        width:120,
                        title:'类型',
                        formatter:'tempObjectFormatter'
                    },
                    {
                        field:'integerappend',
                        width:120,
                        title:'数据权限',
                        formatter:'authorFormatter'
                    },
                    {
                        field:'integerappend',
                        width:150,
                        title:'拦截类型',
                        formatter:'authorTypeFormatter'
                    },
                    {
                        field:'buessid',
                        title:'操作',
                        formatter:'btnFormatter'
                    }
                ],
                onLoadSuccess:function(data){

                }
            });
            closeWating(null,dialogWating);
        }
    });
}

//数据权限
function authorFormatter(value, row, index){
    var integerappend = row.integerappend;
    if(integerappend != null && integerappend != ""){
        var val = integerappend.split(",");
        if(val[0] == 0){
            return "<font color='red'>是</font>";
        }else if(val[0] == 1){
            return "否";
        }
    }
}


function nameFormatter(value, row, index){
    var data = row.tempObject;
    if("Sources" == data){
        return value;
    }
    if("Function" == data){
        return value;
    }
}

function tempObjectFormatter(value, row, index){
    var data = row.tempObject;
    if("Sources" == data){
        return "<span class='label label-lg font-weight-bold label-light-primary label-inline'>资源</span>";
    }
    if("Function" == data){
        return "<span class='label label-lg font-weight-bold label-light-info label-inline'>功能</span>";
    }
    return "缺省";
}

//拦截类型
function authorTypeFormatter(value, row, index){
    var val = value.split(",");
    if(val[1] == 0){
        return "无需拦截"
    }else if(val[1] == 1){
        return "<font color='red'>必须拦截</font>";
    }
}

//格式化按钮
function btnFormatter(value, row, index){
    var tempObject = row.tempObject;
    var name = row.name;
    var fileName = "资源-"+row.name+"-"+value;
    if(tempObject == 'Sources'){
        var btn = '<a class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="导出资源" href=javascript:exportOauthResources("'+value+'","'+fileName+'")><i class="flaticon-download"></i></a>';
        return '<span class="dropdown">' +
                    '<a href="#" class="btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="dropdown" aria-expanded="true">' +
                        '<i class="la la-ellipsis-h"></i>' +
                    '</a>' +
                    '<div class="dropdown-menu dropdown-menu-right">' +
                        '<button class="dropdown-item" onclick=addXtMenuinfo("'+value+'","'+name+'")><i class="la la-edit"></i>添加子资源</button>' +
                        '<button class="dropdown-item" onclick=chXtMenuinfo("'+value+'","'+name+'")><i class="fa fa-edit"></i>设为一级资源</a>' +
                    '</div>' +
                '</span>' +
                '<button onclick=updateXtMenuinfo("'+value+'") class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="编辑">' +
                    '<i class="fa fa-magic fa-lg"></i>' +
                '</button>'+
                '<button onclick=delXtMenuinfo("'+value+'") class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="删除">' +
                    '<i class="fa fa-trash-o"></i>' +
                '</button>'+
                btn

        // return '<a href=javascript:addXtMenuinfo("'+value+'","'+name+'") class="btn btn-default" title="添加子资源"><i class="glyphicon glyphicon-plus">添加子资源</i></a><a href=javascript:chXtMenuinfo("'+value+'","'+name+'") class="btn btn-default" title="设为一级资源"><i class="glyphicon glyphicon-pencil">设为一级资源</i></a><a href=javascript:updateXtMenuinfo("'+value+'") title="编辑" class="btn btn-default"><i class="fa fa-edit">编辑</i></a><a href=javascript:delXtMenuinfo("'+value+'") class="btn btn-default" title="删除"><i class="fa fa-trash-o">删除</i></a>';
    }
}

function chXtMenuinfo(value,valueText){
    msgTishCallFnBoot("确定将资源<font color=red>【"+valueText+"】</font>设为一级资源？",function(){
        var params = {resources_id:value};
        ajaxBRequestCallFn(oauthModules+'/oauthResources/chMenuInfo',params,function(result){
            try {
                if(typeof(result.success) != "undefined"){
                    if(result.success){
                        window.parent.toastrBoot(3,result.message);
                        initSysModeTable();
                    }else{
                        window.parent.toastrBoot(4,result.message);
                    }
                }
            } catch (e) {

            }
        });
    })
}
function delXtMenuinfo(value){
    if(value == null){
        toastrBoot(4,"未能获取该数据编号");
        return;
    }
    msgTishCallFnBoot("确定删除该数据？",function(){
        var params = {resources_id:value, _method:'DELETE'};
        ajaxBRequestCallFn(oauthModules+'/oauthResources/delete',params,function(result){
            try {
                if(typeof(result.success) != "undefined"){
                    if(result.success){
                        window.parent.toastrBoot(3,result.message);
                        initSysModeTable();
                    }else{
                        window.parent.toastrBoot(4,result.message);
                    }
                }
            } catch (e) {

            }
        },null,"DELETE");
    })
}
function expandTree(){
    dialogWating = showWating({msg:'正在操作中...'});
    $('#table').bootstrapTable("expandAllTree")
    closeWating(null,dialogWating);
}
function collapseTree(){
    dialogWating = showWating({msg:'正在操作中...'});
    $('#table').bootstrapTable("collapseAllTree")
    closeWating(null,dialogWating);
}

function changeMenuinfoSelect(){
    var SourcesModalCount = 0 ;
    $('#changeXtMenuinfoBody').height(300);
    $('#changeXtMenuinfoModal').modal({backdrop:'static',keyboard:false});
    $('#changeXtMenuinfoModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        if(++SourcesModalCount == 1) {
            treeObj = $.fn.zTree.init($("#tree"), null,[]);
            $(".ztree").append("暂无数据");
            initComboData("sysmode_id",oauthModules+"/oauthSysMode/listAll","sys_mode_id","sysname");
        }
    });
}
//单击事件
function onClick(event, treeId, treeNode, msg){
}

/**
 * 下拉框变化筛选菜单树
 * @param thiz
 */
function doThisEvent(thiz) {
    var setting = {
        view:{
            selectedMulti:false
        },
        check:{
            enable:false
        },
        data:{
            //必须使用data
            simpleData:{
                enable:true,
                idKey:"id",//id编号命名 默认
                pIdKey:"pId",//父id编号命名 默认
                rootPId:0 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            }
        },
        edit:{
            enable:false
        },
        callback:{
            onClick:onClick//单击事件
        }
    };
    var zTreeNodes;
    dialogWating = showWating({msg:'正在拼命的加载中...'});
    var parm = {"sysmode_id":thiz.value};
    ajaxBRequestCallFn(oauthModules+'/oauthResources/bZTree',parm,function(result){
        zTreeNodes = eval("(" + result.data + ")");
        if(undefined == result.data || null == result.data || result.data == "" || result.data == "[]"){
            treeObj = $.fn.zTree.init($("#tree"), setting,[]);
            $(".ztree").append("暂无数据");
        }else{
            treeObj = $.fn.zTree.init($("#tree"), setting,zTreeNodes);
        }
        closeWating(null,dialogWating);
    },null,"GET");
}

function doXtMenuinfoSel(){
    var id = $('#resources_id').val();
    var zTree = $.fn.zTree.getZTreeObj("tree"),
        nodes = zTree.getSelectedNodes();
    if (nodes.length != 1) {
        toastrBoot(4,"请选择资源");
        return;
    }

    var node = zTree.getNodes();
    var treeNode;
    var nodesarray = zTree.transformToArray(node);
    for(var i = 0; i < nodesarray.length; i++){
        if(nodesarray[i].id == id){
            treeNode = nodesarray[i];
            break;
        }
    }

    if(undefined == treeNode){
        treeNode =  nodes[0];
    }else{
        var result = '';
        result = getChildNodes(treeNode,result);
        result = treeNode.id + ","+result;
        if(result.indexOf(nodes[0].id) >= 0){
            toastrBoot(4,"您选择的上级资源不合法");
            return;
        }
    }

    msgTishCallFnBoot("确定要选择【<font color=red>"+nodes[0].name+"</font>】？",function(){
        $('#resources_parentidTitle_').val(nodes[0].name);
        $('#resources_parentid_').val(nodes[0].id);
        $('#changeXtMenuinfoModal').modal('hide');
    })
}

function InitMenuModuleListSetV(id,value_id){
    $("#"+id).html("");;
    var str = "<option value=''>请选择</option>";

    var params = {};
    ajaxBRequestCallFn(oauthModules+'/oauthSysModules/listAll',params,function(result){
        result = result.data;
        //从服务器获取数据进行绑定
        $.each(result, function(i, item){
            str += "<option value=" + item.sys_modules_id + ">" + item.sysname+ " -----  "+ item.sys_modules_name + "</option>";
        })
        $("#"+id).append(str);
        try {
            if(null != value_id && '' != value_id){
                if('undefined' != typeof($('#'+value_id).val()) && null != $('#'+value_id).val() && '' != $('#'+value_id).val() && '请选择' != $('#'+value_id).val()){
                    $('#'+id).val($('#'+value_id).val());
                }
            }
        } catch (e) {
            console.log("读取下拉框并赋值出现异常，异常信息："+e);
        }
    },null,"POST");
}



/**
 * 导出资源
 * @param resources_id
 * @param fileName
 */
function exportOauthResources(resources_id,fileName) {
    msgTishCallFnBoot("确定要导出该资源？",function(){
        var url = oauthModules+'/oauthResources/export?resources_id='+resources_id; // 请求接口
        var method = "GET"; // 请求方式 GET或POST
        fileName = fileName+".json"; // 下载后的文件名称
        var params = "name='test" // 后台接口需要的参数
        downloadFileCallFn(url, method, fileName,params);
    });
}


/**
 * 导入资源
 */
var oauthResourcesFileUploadResultArray = [];
function importOauthResources() {
    $('#oauthResourcesFileModal').modal({backdrop: 'static', keyboard: false});
    var importOauthResourcesModalCount = 0 ;
    $('#oauthResourcesFileModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        if(++importOauthResourcesModalCount == 1) {
            oauthResourcesFileUploadResultArray.push('0');
            //使用bootstrap-fileinput渲染
            $('#oauthResourcesFile').fileinput({
                language:'zh',//设置语言
                uploadUrl:oauthModules+'/oauthResources/import',//上传的地址
                type: 'POST',
                contentType: "application/json;charset=utf-8",
                enctype: 'multipart/form-data',
                allowedFileExtensions:['json','txt'],//接收的文件后缀
                theme:'fa',//主题设置
                dropZoneTitle:'可以将文件拖放到这里',
                autoReplace: true,//布尔值，当上传文件达到maxFileCount限制并且一些新的文件被选择后，是否自动替换预览中的文件。如果maxFileCount值有效，那么这个参数会起作用。默认为false
                overwriteInitial: true,//布尔值，是否要覆盖初始预览内容和标题设置。默认为true，因此当新文件上传或文件被清除时任何initialPreview内容集将被覆盖。将其设置为false将有助于始终显示从数据库中保存的图像或文件，尤其是在使用多文件上传功能时尤其有用。
                uploadAsync:false,//默认异步上传
                showPreview:true,//是否显示预览
                // showUpload: true,//是否显示上传按钮
                showRemove: true,//显示移除按钮
                showCancel:true,//是否显示文件上传取消按钮。默认为true。只有在AJAX上传过程中，才会启用和显示
                showCaption: true,//是否显示文件标题，默认为true
                browseClass: "btn btn-light-primary font-weight-bold mr-2", //文件选择器/浏览按钮的CSS类。默认为btn btn-primary
                dropZoneEnabled: true,//是否显示拖拽区域
                validateInitialCount: true,
                maxFileSize: 0,//最大上传文件数限制，单位为kb，如果为0表示不限制文件大小
                minFileCount: 1, //每次上传允许的最少文件数。如果设置为0，则表示文件数是可选的。默认为0
                maxFileCount: 0, //每次上传允许的最大文件数。如果设置为0，则表示允许的文件数是无限制的。默认为0
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",//当检测到用于预览的不可读文件类型时，将在每个预览文件缩略图中显示的图标。默认为<i class="glyphicon glyphicon-file"></i>
                previewFileIconSettings: {
                    'docx': '<i ass="fa fa-file-word-o text-primary"></i>',
                    'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                    'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                    'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                    'jpg': '<i class="fa fa-file-photo-o text-warning"></i>',
                    'pdf': '<i class="fa fa-file-archive-o text-muted"></i>',
                    'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
                },
                uploadExtraData: function () {
                    return {
                        name: 'test'
                    }; //上传时额外附加参数
                },
                // msgSizeTooLarge: "文件 '{name}' (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.",
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",//字符串，当文件数超过设置的最大计数时显示的消息 maxFileCount。默认为：选择上传的文件数（{n}）超出了允许的最大限制{m}。请重试您的上传！
                // elErrorContainer:'#kartik-file-errors',
                ajaxSettings:{
                    headers:{
                        "token":getToken()
                    }
                }
            }).on('change',function () {
                // 清除掉上次上传的图片
                $(".uploadPreview").find(".file-preview-frame:first").remove();
                $(".uploadPreview").find(".kv-zoom-cache:first").remove();
            }).on('fileuploaded',function (event,data,previewId,index) {//异步上传成功处理
                console.log('单个上传成功，并清空上传控件内容',data,previewId,index);
                for(var i = 0; i < oauthResourcesFileUploadResultArray.length; i++){
                    if(i == 0){
                        //清除文件输入 此方法清除所有未上传文件的预览，清除ajax文件堆栈，还清除本机文件输入
                        $('#oauthResourcesFile').fileinput('clear');
                        $('#oauthResourcesFile').fileinput('clear').fileinput('disable');
                        window.parent.toastrBoot(3,data.response.message);
                        //关闭文件上传的模态对话框
                        $('#oauthResourcesFileModal').modal('hide');
                        //重新刷新bootstrap-table数据
                        search('datatables')
                        oauthResourcesFileUploadResultArray.splice(0,oauthResourcesFileUploadResultArray.length);
                        i--;
                        break;
                    }
                }
            }).on('fileerror',function (event,data,msg) { //异步上传失败处理
                console.log('单个上传失败，并清空上传控件内容',data,msg);
                window.parent.toastrBoot(4,"上传文件失败！");
            }).on('filebatchuploadsuccess', function(event, data, previewId, index) {
                console.log('批量上传成功，并清空上传控件内容',data,previewId,index);
                $('#oauthResourcesFile').fileinput('clear');
                $('#oauthResourcesFile').fileinput('clear').fileinput('disable');
                window.parent.toastrBoot(3,data.response.message);
                //关闭文件上传的模态对话框
                $('#oauthResourcesFileModal').modal('hide');
                //重新刷新bootstrap-table数据
                search('datatables')
            }).on('filebatchuploaderror', function(event, data, msg) {
                //批量上传失败，并清空上传控件内容
                console.log('批量上传失败，并清空上传控件内容',data,msg);
            }).on("filebatchselected", function (event, data, previewId, index) {
                console.log('选择文件',data,previewId,index);
            })/*.on('filepreajax', function(event, previewId, index) {
                var container = $("#divId");
                var oauthFunctionInfoDiv = container.find('.kv-upload-progress');
                oauthFunctionInfoDiv.hide();
                $('#oauthFunctionInfoFile').fileinput('enable');
                return false;
            })*/;
        }
    });
}

/**
 * 关闭窗体
 */
function closeOauthResourcesFileWin() {
    $("#oauthResourcesFile").fileinput('reset'); //重置上传控件（清空已文件）
    $('#oauthResourcesFile').fileinput('clear');
    //关闭上传窗口
    $('#oauthResourcesFileModal').modal('hide');
}